package com.example.hello.config;

import com.example.hello.util.JwtTokenUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * JWT认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 不需要验证的路径
     */
    private final List<String> excludedPaths = Arrays.asList(
            "/login",
            "/emps/login");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        // 如果是排除的路径，直接放行
        String path = request.getRequestURI();
        for (String excludedPath : excludedPaths) {
            if (path.equals(excludedPath)) {
                chain.doFilter(request, response);
                return;
            }
        }

        // 获取Authorization头
        final String requestHeader = request.getHeader("Authorization");

        String username = null;
        String token = null;

        // 检查Authorization头是否存在且格式正确
        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
            token = requestHeader.substring(7);
            if (StringUtils.hasText(token)) {
                try {
                    // 从token中获取用户名
                    username = jwtTokenUtil.getUsernameFromToken(token);
                } catch (Exception e) {
                    logger.error("Token验证失败", e);
                }
            }
        }

        // 如果token验证成功，设置用户信息到请求属性中
        if (username != null && jwtTokenUtil.validateToken(token)) {
            // 将用户信息存储到请求属性中，供后续使用
            request.setAttribute("username", username);
            request.setAttribute("userId", jwtTokenUtil.getUserIdFromToken(token));
        }

        chain.doFilter(request, response);
    }
}